package org.dding.msc.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.dding.core.util.StringUtils;

@SuppressWarnings("rawtypes")
public class ServiceInfoWarehouse {

	private static ServiceInfoWarehouse serviceInfoHouse = new ServiceInfoWarehouse();

	public static ServiceInfoWarehouse getInstance() {
		return serviceInfoHouse;
	}

	Object monitor = new Object();
	private ConcurrentHashMap<String, ServiceInfo> wm = new ConcurrentHashMap<String, ServiceInfo>();
	private ConcurrentHashMap<String, List<String>> moduleByService = new ConcurrentHashMap<String, List<String>>();

	public void registry(String serviceName, ServiceInfo serviceInfo) {

		synchronized (monitor) {
			wm.putIfAbsent(serviceName, serviceInfo);
			if (StringUtils.isEmpty(serviceInfo.moduleName))
				return;
			List<String> services = moduleByService.get(serviceInfo.moduleName);
			if (services == null) {
				services = new ArrayList<String>();
			}
			services.add(serviceName);
			moduleByService.put(serviceInfo.moduleName, services);
		}
	}

	public ServiceInfo get(String serviceName) {
		return wm.get(serviceName);
	}

	public void remove(String serviceName) {
		synchronized (monitor) {
			ServiceInfo serviceInfo = wm.remove(serviceName);
			if (serviceInfo == null)
				return;
		}
	}
	public void clear(String moduleName){
		moduleByService.remove(moduleName);
	}

	public List<String> getServiceByModule(String moduleName) {
		return moduleByService.get(moduleName);
	}

	public class ServiceInfo {

		public ServiceInfo(Class<? extends Service> serviceClass,
				String moduleName) {
			super();
			this.serviceClass = serviceClass;
			this.moduleName = moduleName;
		}

		public Class<? extends Service> serviceClass;
		public String moduleName;
	}
}
